package model.repository

import androidx.compose.runtime.MutableState
import com.google.gson.Gson
import model.db.Db
import model.dto.UserDto
import model.network.Network
import model.vo.UserVo
import model.enums.ThemeType
import state.WindowType
import theme.EasyChatTheme
import ui.login.LoginViewModel

object UserRepository {
    var user: UserVo? = null
    var token: String? = null
    var friendUserVOList: MutableList<UserVo> = mutableListOf()
    var theme: ThemeType = ThemeType.Blue

    suspend fun login(viewModel: LoginViewModel, easyChatTheme: MutableState<EasyChatTheme>) {
        try {
            //进行登陆请求，这是一个挂起函数
            val login = Network.userService.login(UserDto(viewModel.userAccount.value, viewModel.userPassword.value))
            if (login.code == 200) {
                //登陆成功，保存用户信息
                token = login.data?.token
                user = login.data?.userMsg
                user?.let { friendUserVOList.add(it) }
                user?.account?.let { ChannelMappingRepository.channelMappingAccountList.add(it) }
                println("token:${token}")
                println("userVO:${Gson().toJson(user)}")
                //保存用户信息
                Db.saveUser(user!!, viewModel.userPassword.value)
                user?.account?.let { Db.saveLastLoginAccount(it) }
                //进入主界面，关闭登陆界面
                easyChatTheme.value=EasyChatTheme(theme)
                viewModel.applicationWindowsState.newWindow(WindowType.HOME)
                viewModel.applicationWindowsState.close(WindowType.LOGIN)
            } else {
                //登陆失败，弹出提示
                viewModel.loginStateDialogShow.value = true
                viewModel.loginStateDialogMsg.value = login.msg.toString()
            }
        } catch (e: Exception) {
            //登陆失败，网络错误
            viewModel.loginStateDialogShow.value = true
            viewModel.loginStateDialogMsg.value = "网络错误"
            e.printStackTrace()
        } finally {
            viewModel.loginBtnEnable.value = true
        }
    }
}